var express = require('express');
var router = express.Router();
const fs = require('fs');

const nodeExcel = require('excel-export'); //引入 excel-export

//活动结束之后导出表格，记录中奖人员
router.post('/', function (request, response, next) {

    //开启 promise 异步读取文件内容
    new Promise((resolve, reject) => {

        fs.readFile(__dirname + '/../public/file/result.txt', (err, data) => {

            if (err) {

                reject(err)
                return;

            }

            let res = data.toString();
            resolve(res);

        })


    })
        .then(res => {

            let exportResults;
            
            if (res != '') {
                
                let tmpTotalArr = [];
                let arr = res.split('<&&;').splice(1); //以定界符： <&&; 为标识，分割读取出来的数据为数组

                for (let k = 0; k < arr.length; k++) {

                    let el = arr[k];

                    let tmpArr = new Array();
                    let tmpEl = JSON.parse(el); //解析读取出来的数据

                    for (let i = 0; i < tmpEl.list.length; i++) { //数据重组，便于读取

                        let item = tmpEl.list[i];
                        item.identifier = tmpEl.identifier;
                        item.sort = '第 ' + (i + 1) + ' 名';
                        tmpArr.push(item);

                    }

                    tmpTotalArr.push(tmpArr);

                }

                exportResults = exportData(tmpTotalArr); // 生成 nodeExcel 要的数据

            }else{

                let tmpArr = emptyData();

                exportResults = tmpArr;
            }

            let result = nodeExcel.execute(exportResults); // nodeExcel 生成的数据

            response.setHeader('Content-Type', 'application/vnd.openxmlformats');
            response.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            response.end(result, 'binary'); //返回给前台

        })
        .catch(err => {
            console.log(err);
        })

    function exportData(arr) {

        let confs = new Array();

        for (let k = 0; k < arr.length; k++) {

            let conf = {};

            conf.name = 'sheet' + (k + 1);// sheet 名称

            let alldata = new Array();
            let tmpArr = arr[k];

            for (let i = 0; i < tmpArr.length; i++) {

                let arr = new Array();
                arr.push(tmpArr[i].phone);
                arr.push(tmpArr[i].curCode);
                arr.push(tmpArr[i].identifier);
                arr.push(tmpArr[i].sort);
                arr.push(tmpArr[i].count);
                alldata.push(arr);

            }

            //决定列名和类型
            conf.cols = [

                {
                    caption: '手机号',
                    type: 'string'
                }, {
                    caption: '代号',
                    type: 'number'
                }, {
                    caption: '场次标识',
                    type: 'string'
                }, {
                    caption: '排名',
                    type: 'string'
                }, {
                    caption: '次数',
                    type: 'number'
                }

            ];

            conf.rows = alldata;//填充数据

            confs.push(conf); //有几个 sheet 填充几次

        }
        return confs;
    }

    function emptyData(){

        let conf = {};
        conf.name = 'sheet';
        conf.cols = [

            {
                caption: '手机号',
                type: 'string'
            }, {
                caption: '代号',
                type: 'number'
            }, {
                caption: '场次标识',
                type: 'string'
            }, {
                caption: '排名',
                type: 'string'
            }, {
                caption: '次数',
                type: 'number'
            }

        ];
        conf.rows = [];

        return conf;

    }
})

module.exports = router;

